package com.java202411.service.user;


import com.java202411.entity.UserEntity;
import com.java202411.repository.UserRepository;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Validated
public class UserService {
    private final UserRepository userRepository;

    public UserEntity createUser(
            @NotNull @Email String email, @Pattern(regexp = "[a-zA-Z0-9]{16,30}") @NotNull String password
    ) {
        Optional<UserEntity> existedUser = this.userRepository.findByEmail(email);
        if (existedUser.isPresent()) {
            throw new DuplicationEmailException("email 重复");
        }

        UserEntity user = UserEntity.builder()
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .email(email)
                .password(password)
                .build();
        return userRepository.save(user);
    }

    public Optional<UserEntity> findByEmail(String email) {
        return this.userRepository.findByEmail(email);
    }
}
